package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author xunyuhua
 * @since 2022-06-28
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private MinIOService minIOService;

    @Override
    public ResponseResult saveWmMaterial(MultipartFile file) {
        // 从本地线程中获取当前的用户id
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String url = minIOService.upload(file);
        WmMaterial wmMaterial = new WmMaterial();
//        wmMaterial.setId();
        wmMaterial.setUserId(user.getUserId());
        wmMaterial.setUrl(url);
        wmMaterial.setType(0);
        wmMaterial.setIsCollection(false);
        wmMaterial.setCreatedTime(new Date());
        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult list(WmMaterialDto dto) {
        // 从本地线程中获取当前的用户id
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //构建查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        //判断是否加入了收藏状态
        if (dto.getIsCollection() != null) {
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //隐藏条件，当前用户只能查询到自己的图片
        queryWrapper.eq(WmMaterial::getUserId,user.getUserId());
        //对查询结果进行排序，根据创建时间倒序排序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //构建分页条件
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        //分页查询
        Page<WmMaterial> page1 = this.page(page,queryWrapper);

        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());

    }
}
